package com.heima.user.service.impl;

import java.util.Date;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.admin.AdminConstants;
import com.heima.common.exception.CustException;
import com.heima.feigns.AuthorFeign;
import com.heima.feigns.WemediaFeign;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.AuthDTO;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserRealnameService;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author lo
 * @date 2021/9/21
 */
@Service
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {
    /**
     * 根据状态查询实名认证列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult getList(AuthDTO dto) {
        //1.校验参数
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        dto.checkParam();

        //2. 构建查询条件
        LambdaQueryWrapper<ApUserRealname> wrapper = Wrappers.lambdaQuery();
        if (dto.getStatus() != null) {
            wrapper.eq(ApUserRealname::getStatus, dto.getStatus());
        }
        //3.根据条件分页查询
        IPage<ApUserRealname> page = new Page<>();
        this.page(page, wrapper);
        //4.封住数据并返回
        return new PageResponseResult(dto.getPage(), dto.getSize(), page.getTotal(), page.getRecords());
    }


    @Autowired
    ApUserMapper apUserMapper;

    @GlobalTransactional(rollbackFor = Exception.class)
    @Override
    public ResponseResult updateStatusById(AuthDTO dto, Short status) {
        //1.校验id
        if (dto.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //2.根据id查询实名认证表是否有这调数据
        ApUserRealname realName = this.getById(dto.getId());
        //3.检查状态
        //检查是不是待审核的数据
        if (!realName.getStatus().equals(AdminConstants.WAIT_AUTH)) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "实名认证状态错误");
        }

        //4.查询关联的apuser的信息
        ApUser apUser = apUserMapper.selectById(realName.getId());
        if (apUser == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "用户关联的信息不存在");
        }

        //5.修改实名认证的状态
        realName.setStatus(status);
        if (Strings.isNotBlank(dto.getMsg())) {
            realName.setReason(dto.getMsg());
        }
        updateById(realName);
        // 1 待审核   2 审核失败  9 审核通过
        //6.判断是否为通过状态
        if (realName.getStatus().equals(AdminConstants.PASS_AUTH)) {
            // 开通自媒体账号
            WmUser wmUser = createWmUser(apUser);
            //  创建作者信息
            createAuthor(wmUser, apUser);
        }
        // 事务完成
        // int i = 1/0;
       return ResponseResult.okResult();
    }

    @Autowired
    AuthorFeign authorFeign;

    /**
     * 远程创建创建对应作者信息
     *
     * @param wmUser 自媒体账户的信息
     * @param apUser app端账户的信息
     */
    private void createAuthor(WmUser wmUser, ApUser apUser) {
        //1.查询作者信息是否已经存在
        ResponseResult<ApAuthor> authorResponseResult = authorFeign.findByUserId(wmUser.getId());

        //2.判断是否查询成功
        if (authorResponseResult.getCode().intValue() != 0) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR, authorResponseResult.getErrorMessage());
        }
        //3.获取作者信息
        ApAuthor author = authorResponseResult.getData();
        if (author != null) {
            //说明作者信息已经存在
            CustException.cust(AppHttpCodeEnum.DATA_EXIST, "对应的作者账户已经存在");
        }
        //说明作者信息不存在,那就创建作者信息
        author = new ApAuthor();
        author.setName(apUser.getName());
        author.setType(2);
        author.setUserId(apUser.getId());
        author.setCreatedTime(new Date());
        author.setWmUserId(wmUser.getId());

        //保存作者信息
        ResponseResult save = authorFeign.save(author);
        if (save.getCode().intValue() != 0) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }


    }

    @Autowired
    WemediaFeign wemediaFeign;

    /**
     * 远程创建自媒体用户
     *
     * @param apUser
     * @return
     */
    private WmUser createWmUser(ApUser apUser) {
        //查询关联自媒体踢账户是否存在
        ResponseResult<WmUser> wmUserResponseResult = wemediaFeign.findByName(apUser.getName());
        if (wmUserResponseResult.getCode() != 0) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR, wmUserResponseResult.getErrorMessage());
        }
        WmUser data = wmUserResponseResult.getData();

        if (data != null) {
            CustException.cust(AppHttpCodeEnum.DATA_EXIST, "对应的自媒体账户已经存在");
        }
        //创建自媒体账户
        data = new WmUser();
        data.setId(apUser.getId());
        data.setName(apUser.getName());
        data.setPassword(apUser.getPassword());
        data.setSalt(apUser.getSalt());
        data.setImage(apUser.getImage());
        data.setPhone(apUser.getPhone());
        data.setStatus(9);
        data.setType(0);
        data.setCreatedTime(new Date());

        //添加自媒体用户
        ResponseResult<WmUser> save = wemediaFeign.save(data);
        if (save.getCode().intValue() != 0) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR, wmUserResponseResult.getErrorMessage());
        }

        //已经设置了id的wmuser对象
        return save.getData();

    }
}
